﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MarginTrading.Entity;
using MarginTrading.Services;

namespace MarginTrading.Forms
{
    public partial class GenerateAccBalFile : Form
    {
        public GenerateAccBalFile()
        {
            InitializeComponent();
        }

        private void CancelBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void UploadBtn_Click(object sender, EventArgs e)
        {
            if (DestinationFolder.Text == "")
            {
                MessageBox.Show("Destination folder is empty");
            }
            String AgentName = "";

            try
            {
                Config BrokerCodeConfig = ConfigServices.GetConfigByName("Agent Code");
                AgentName = BrokerCodeConfig.Value.Trim();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Database Error occurred.", "Error");

            }

            System.IO.StreamWriter file = null;
            try
            {
                List<String> Coll = ClientService.GetClientCodeCol(AgentName);
                file = new System.IO.StreamWriter(DestinationFolder.Text + "\\Balance_" + AgentName + "_" + dateTimePicker1.Value.ToString("yyyyMMdd") + ".txt");
                    
                foreach (String cli in Coll)
                {
                    String client = cli.Substring(4);
                    client = client.PadLeft(15, '0');
                    Double LoanBalance = LoanAccountServices.GetCurrentBalance(cli);
                    LoanBalance = LoanBalance + DailyInterestServices.GetDailyInterestByClientCode(cli);

                    Double FutureBalance = SettlementDetailsServices.GetFutureBalance(cli);

                    file.WriteLine(dateTimePicker1.Value.ToString("yyyyMMdd") + client +
                        String.Format("{0,18:0.00}", LoanBalance) + String.Format("{0,18:0.00}", FutureBalance));
                }
                MessageBox.Show(Coll.Count +" records were written to the file", "Message");

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message,"Error");
            	
            }
            finally
            {
                file.Close();
            }
        }

        private void FoldetBrwsBtn_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                DestinationFolder.Text = folderBrowserDialog1.SelectedPath;
            }
        }
    }
}
